using System;
using System.Collections.Generic;
using ETModel;
using UnityEngine;
using UnityEngine.UI;


namespace View.Instant
{
    public class HallView : View
    {
        private Button m_btnHead;
        private Button m_btnHead_kuang;
        private Text m_txtGold;

        public Image demo;
        private Text mtxtPlayerName;
        public Text txt_MonyBouns;

        //public Text txt_percentage;

        //public Text txt_tips;
		
		public Text txt_vip;
       
        private RawImage mimgHead;


        private Button btn_FirstRecharge;

        private GameObject image_Weekly;

        private GameObject WeeklyTime;

        private Text txt_weeklyTime;

        private Button btn_Withdraw;
        private Button mbtnExtensionOfficer;

        private List<float> bottom_List = new List<float>() { 114,308,478,652, 861 , 1080 , 1307 , -643 , -272 };

        //private Dictionary<string, bool> DownloadList = new Dictionary<string, bool>();

        private Dictionary<string, GameObject> mRedPointDic = new Dictionary<string, GameObject>();

        public Dictionary<string, Action<string, string, float>> downLoadDic = new Dictionary<string, Action<string, string, float>>();
        /// <summary>
        /// 字典
        /// </summary>
        private Dictionary<int, GameObject> gameItemDic = new Dictionary<int, GameObject>();
        
        //点击游戏的时候检测一下是不是下载过，下载过就进入，没有就下载
        private Dictionary<ushort, Action> mClickGameIconDic = new Dictionary<ushort, Action>();

        private int mTaskMoveUp = 0;
		float SixteenToNineRatio = 16f / 9f;
        public Transform panel_bottom;
        /// <summary>
        /// 加载
        /// </summary>
        public override void OnLoad()
        {
            Debug.Log("================OnLoad=============="+Screen.width/Screen.height);
            float screenWidth = Screen.width;
            float screenHeight = Screen.height;

            // 计算屏幕的宽高比
            float screenRatio = screenWidth / screenHeight;

            // 如果屏幕宽高比接近 16:9，则输出屏幕比例正确
            if (!Mathf.Approximately(screenRatio, SixteenToNineRatio)&&(screenRatio > SixteenToNineRatio))
            {
                panel_bottom = transform.Find("root/panel_bottom").transform;
                for (int i = 0; i < panel_bottom.transform.childCount; i++)
                {
                    panel_bottom.transform.GetChild(i).GetComponent<RectTransform>().anchoredPosition = new Vector3(bottom_List[i], panel_bottom.transform.GetChild(i).transform.localPosition.y);
                }
            }

            Utils.OnDownLoadGameFiles((fileName, msg, progress) =>
            {
                if (downLoadDic.ContainsKey(fileName))
                {
                    downLoadDic[fileName]?.Invoke(fileName, msg, progress);
                }
            });
            GlobalUserItem.KindID = 0;
            GlobalUserItem.isDownLoadGame = false;
            UIManager.Instance.CloseWait();
            //demo = transform.Find("DEMO").GetComponent<Image>();
            base.OnLoad();
            OnInit();
            AddButtonClick();
            Debug.LogError("开始播放背景音乐");
            Debug.LogError("播放背景音乐结束");
            OnFirstGetHttpData();
            InitView();
            AddEventListener();
            GlobalUserItem.szWalletPhone = "";
            //demo.sprite = ResourceManager.Instance.LoadUISprites("Hall/Textures/Common", "UI_Common_tps")[1];

            //暂时不要删除的，因为在进入游戏的时候也需要调用update来计时 ，所以暂时不用删除，在destroy的时候删除
        }

        /// <summary>
        /// AddEventListener
        /// </summary>
        private void AddEventListener()
        {
        }

        public void OnUpdataBounsInfo()
        {

        }


        private void OnInit()
        {
            m_btnHead = transform.Find("root/panel_up/head/img_icon_di_ku").GetComponent<Button>();
            m_btnHead_kuang = transform.Find("root/panel_up/head/img_kuang_head").GetComponent<Button>();
            m_txtGold = transform.Find("root/panel_up/head/go_jinbi/img_di/text_gold").GetComponent<Text>();
            txt_MonyBouns= transform.Find("root/panel_bottom/btn_bouns/di/money_txt").GetComponent<Text>();
            mtxtPlayerName = transform.Find("root/panel_up/head/text_nick_name").GetComponent<Text>();
            //txt_percentage =  transform.Find("root/btn_refer_now/txt_percentage").GetComponent<Text>();
            //txt_tips = transform.Find("root/btn_refer_now/txt_tips").GetComponent<Text>();
            mimgHead = transform.Find("root/panel_up/head/img_icon_di/img_head_icon").GetComponent<RawImage>();
            btn_FirstRecharge = transform.Find("root/panel_bottom/btn_FirstRecharge").GetComponent<Button>();
            image_Weekly = btn_FirstRecharge.transform.Find("image_Weekly").gameObject;
            WeeklyTime = btn_FirstRecharge.transform.Find("Time").gameObject;
            txt_weeklyTime = WeeklyTime.transform.Find("txt_Time").GetComponent<Text>();

            btn_Withdraw= transform.Find("root/panel_up/btn_Withdraw").GetComponent<Button>();
            mbtnExtensionOfficer = transform.Find("root/panel_bottom/btn_refer_san").GetComponent<Button>();
            
        	txt_vip= transform.Find("root/panel_up/left/btn_vip/text_vip").GetComponent<Text>();
        }

        /// <summary>
        /// AddButtonClick
        /// </summary>
        private void AddButtonClick()
        {

        }
        private void LoadData()
        {
            PopActivityManager.Instance().OnResetPopActList();
            
        }

        public void InitViewInfo()
        {
            m_txtGold.text = "₹"+ Utils._GMoneyFormatDouble(GlobalUserItem.lUserScore);
            mtxtPlayerName.text = GlobalUserItem.szNickName;
            _G["text_game_id"].GetComponent<Text>().text = "ID:"+ GlobalUserItem.dwGameID;
            OnUpdataBounsInfo();
            GlobalUserItem.KindID = 0;
        }

        List<ushort> curryDic = new List<ushort>() { 246, 536, 145, 150, 151, 534, 149, 537, 148, 535, 147, 533, 245,250 };
        

        Dictionary<ushort, GameObject> gameAllobj = new Dictionary<ushort, GameObject>();
        /// <summary>
        /// InitView(初始化页面)
        /// </summary>
        public void InitView()
        {
            // _G["text_gold"].GetComponent<Text>()
           

            if (gameItemDic.Count <= 0)
            {
                Debug.LogError("===============InitView(初始化页面)========================");

                {
    
                    //
                    // // //// GameUtilty.Info("pairInfo.Value.wKindID------{0}",pairInfo.Value.wKindID);
                    // GameObject gameItem = GameObject.Instantiate(
                    //      ResourceManager.Instance.LoadPrefab("hall/prefab/hallview",
                    //         "game_" + pairInfo.Value.wKindID), _G["transform_game_content"]);
                    // gameItem.transform.GetComponent<RectTransform>().localScale = Vector3.one;
                    // gameItemDic.Add(pairInfo.Value.wKindID, gameItem);
                    // gameItem.transform.GetComponent<ButtonDragComponent>().enabled = true;
                    // gameItem.transform.GetComponent<ButtonDragComponent>().onClick.RemoveAllListeners();
                    // if (!gameAllobj.ContainsKey(pairInfo.Value.wKindID))
                    // {
                    //     gameAllobj.Add(pairInfo.Value.wKindID, gameItem);
                    // }
                    // string gameName = $"game{pairInfo.Value.wKindID}";
                    // bool needUpdate = false;
                    // Transform mask = null;
                    // Transform IsDown_Obj = null;
                    // if (Utils.IsUpdate)
                    // {
                    //     needUpdate = PlayerPrefs.GetInt(gameName, -1) != Utils.version.smallVersion;
                    //     mask = gameItem.transform.Find("Mask");
                    //     //mask?.gameObject.SetActive(needUpdate);
                    //     IsDown_Obj = gameItem.transform.Find("is_down");
                    //     IsDown_Obj?.gameObject.SetActive(needUpdate);
                    // }
                    // gameItem.transform.GetComponent<ButtonDragComponent>().enabled = true;
                    //
                    // mClickGameIconDic.Add(pairInfo.Value.wKindID, () =>
                    // {
                    //     Debug.LogError("子游戏下载");
                    //     if (!GlobalUserItem.joinRoomList.Any(x => x == gameName))
                    //     {
                    //         GlobalUserItem.joinRoomList.Add(gameName);
                    //     }
                    //    
                    //     if (Utils.IsUpdate)
                    //         needUpdate = PlayerPrefs.GetInt(gameName, -1) != Utils.version.smallVersion;
                    //     if (needUpdate&&Utils.IsUpdate)
                    //     {
                    //         Debug.LogError("点击");
                    //         if (mask!=null)
                    //         {
                    //             mask?.gameObject.SetActive(true);
                    //             Image img = mask.Find("Img").GetComponent<Image>();
                    //             img.fillAmount = 0;
                    //             mask.Find("txt_proress").GetComponent<Text>().text = "0%";
                    //             string key = gameName + ".txt";
                    //             //if (!DownloadList.ContainsKey(gameName))
                    //             //{
                    //             //    DownloadList.Add(gameName,true);
                    //             //}
                    //             downLoadDic[key] = (fileName, msg, progress) =>
                    //             {
                    //                 Debug.LogError("玩家已经进入房间1111");
                    //                 //if (GlobalUserItem.KindID != 0)
                    //                 //{
                    //                 //    Debug.LogError("玩家已经进入房间");
                    //                 //    return;
                    //                 //}
                    //                 Debug.LogError("==========================" + fileName+"=================="+ gameName+"===================="+progress);
                    //                 if (fileName == key)
                    //                 {
                    //                     Debug.LogError("==========================" + progress);
                    //                     mask?.gameObject.SetActive(true);
                    //                     //GlobalUserItem.isDownLoadGame = true;
                    //                     img.fillAmount = progress;
                    //                     string uu = progress.ToString("F2");
                    //                     mask.Find("txt_proress").GetComponent<Text>().text = float.Parse(uu) * 100 + "%";
                    //                     if (progress == 1)
                    //                     {
                    //                         
                    //                         Debug.LogError("下载好游戏名字为================================" + fileName);
                    //                         //GlobalUserItem.isDownLoadGame = false;
                    //                         IsDown_Obj?.gameObject.SetActive(false);
                    //                         mask?.gameObject.SetActive(false);
                    //                         Debug.LogError("子游戏下载===================完成");
                    //                     }
                    //                 }
                    //             };
                    //         }
                    //        
                    //         Utils.DownLoadGameFiles($"{gameName}.txt", () =>
                    //         {
                    //             Debug.LogError("子游戏下载===================完成===储存版本号");
                    //             PlayerPrefs.SetInt(gameName, Utils.version.smallVersion);
                    //             
                    //             Debug.LogError("子游戏下载===================完成===储存版本号==============进游戏");
                    //             mask?.gameObject.SetActive(false);
                    //             IsDown_Obj?.gameObject.SetActive(false);
                    //             
                    //             if (isiInspectRoom(gameName)&&!GameClientManager.Instance().IsInGame())
                    //             {
                    //                 GameClient.Instance.CloseSocketAndRelease();
                    //                 GameButtonClicked(pairInfo.Value.wKindID);
                    //             }
                    //             Debug.LogError("子游戏下载===================完成===储存版本号==============进游戏=======结束");
                    //         });
                    //     }
                    //     else
                    //     {
                    //         Debug.LogError("子游戏下载===================2222");
                    //         GameClient.Instance.CloseSocketAndRelease();
                    //         GameButtonClicked(pairInfo.Value.wKindID);
                    //         Debug.LogError("子游戏下载===================3333333");
                    //     }
                    // });
                    //
                    // gameItem.transform.GetComponent<ButtonDragComponent>().onClick.AddListener(() =>
                    // {
                    //     if (mClickGameIconDic.ContainsKey(pairInfo.Value.wKindID))
                    //     {
                    //         mClickGameIconDic[pairInfo.Value.wKindID]();
                    //     }
                    // });
                }

                ///尽请期待
                string loadpath = "game_new";
                #if UNITY_WEBGL
                    loadpath = "game_download";
                #endif
                GameObject gameItem_ = GameObject.Instantiate( ResourceManager.Instance.LoadPrefab(
                    "hall/prefab/hallview",
                    loadpath), _G["transform_game_content"]);
                gameItem_.transform.GetComponent<RectTransform>().localScale = Vector3.one;
                gameItem_.transform.GetComponent<ButtonDragComponent>().onClick.RemoveAllListeners();
                gameItem_.transform.GetComponent<ButtonDragComponent>().onClick.AddListener(() =>
                {
                    #if UNITY_WEBGL
                        string str = "This reward can only be found in the app. Please download and install the app before claiming it.";
                        CommonPopConfig config = new CommonPopConfig();
                        config._contentList = new List<string>() { str };
                        config.type = 6;
                        config._isNo = false;
                        config._isYes = true;
                        config._funcYes = () => {Application.OpenURL("https://dlgame.dawnpioneerteam.team/apk/teenpattibliss_w2a.apk");};
                        config._txtYes = "App Download";
                        UIManager.Instance.Show(ViewName.CommonPopView, ViewLayer.Middle, config);
                        return;
                    #endif
                });

                gameItemDic.Add(-1, gameItem_);


                _G["scrollView_game"].GetComponent<ScrollRect>().horizontalNormalizedPosition = 0;
            }



            UpdateHot();
            // _G["img_head_icon"].GetComponent<RawImage>().texture =
            //     await UIManager.Instance.LoadTexture("hall/textures/Common/head", "img_" + (GlobalUserItem.wFaceID + 1));
            HeadsManager.Instance().OnLoadSelfHead(mimgHead,GlobalUserItem.dwCustomID,GlobalUserItem.wFaceID);
        }


        public void UpdateHot()
        {

        }
        /// <summary>
        /// 检查再不是在下载列表内
        /// </summary>
        /// <param name="gamekind"></param>
        /// <returns></returns>
        public bool isiInspectRoom(string gamekind)
        {
            for (int i = 0; i < GlobalUserItem.joinRoomList.Count; i++)
            {
                if (gamekind== GlobalUserItem.joinRoomList[i])
                {
                    Debug.LogError("检查之后=============在列表内");
                    return true;
                }
            }
            Debug.LogError("检查之后=============不==在列表内");
            return false;
        }
        /// <summary>
        /// GameButtonClicked
        /// </summary>
        /// <param name="gameName"></param>
        private void GameButtonClicked(ushort wKindID)// tagU3DGameKind tag
        {
            Debug.LogError("点击游戏==================");

            if (wKindID!=null)
            {
                Debug.LogError("游戏Kind====="+wKindID);
            }

            if (wKindID!=246 && wKindID != 250)
            {
                UIManager.Instance.ShowWait(10);
            }
            
            switch (wKindID)
            {
                case 145: //龙虎斗
                {
                        Debug.LogError("开始进游戏145");
                        //UIManager.Instance.ShowWait(10);
                    break;
                }
                case 147: //SinglePatti
                {
                    break;
                }
                case 148: //AndarBahar
                {
                    break;
                }
                case 149: //7UpDown
                {
                    break;
                }
                case 150: //Crash
                {
                    break;
                }
                case 151: //Crash
                {
                    break;
                }
                case 250: //Ludo
                {
                    break;
                }
                case 245: //Rummy13Cards
                {
                    break;
                }
                case 246: //TeenPatti
                {
                    break;
                }
                case 533: //水果玛丽
                {
                        Debug.LogError("开始进游戏533");
                    break;
                }
                case 534: //DiamondSlot
                {
                        Debug.LogError("开始进游戏534");
                    break;
                }
                case 535: //FashionSlot
                {
                        Debug.LogError("开始进游戏535");
                    break;
                }
                case 536: //Mine
                {
                    break;
                }
                case 537: //CircleSlot
                {
                        Debug.LogError("开始进游戏537");
                    break;
                }
                default:
                    ////GameUtilty.Error("未知游戏ID{0}", tag.wKindID);
                    break;
            }
            Debug.LogError("进游戏结束=-----------");
        }

        

        int TimeIndexs = -1;
        public int lastTimes = 0;
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="args"></param>
        public override void OnShow(params object[] args)
        {
            //Debug.LogError("******222*****");
            
            if (AudioSystem.Instance==null)
            {
                Debug.LogError("播放音乐组件为空");
            }
            AudioSystem.Instance.PlayBgm("Hall/Audios", "background0");
            UIManager.Instance.CloseWait();
            base.OnShow(args);
            InitViewInfo();
            //Debug.LogError("===================================================Onshow==========" + downLoadDic.Count);
            SendReferEarnHallReawrdPop();
            OnShareRewardHttpData();
            OnShowMailRedPoint();
            OnInitActivityRedPoint();
           
            if (GlobalUserItem.cbIsNewUser == 1)
            {
                // UIManager.Instance.Show(ViewName.NewBenefitView, ViewLayer.Normal);
            }
            else
            {
                LoadData();
            }
            UpdateFristInfo();
            UpdateHot();
        }
		public void UpdateFristInfo()
        {
            Debug.LogError("现在进来了=============================UpdateInfo=========");
            

        }
        int CalculateRemainingSeconds(DateTime endTime)
        {
            // 获取当前时间
            DateTime currentTime = DateTime.UtcNow;

            // 计算剩余时间间隔
            TimeSpan remainingTimeSpan = endTime - currentTime;

            // 如果当前时间已经超过了结束时间，则剩余秒数为负数
            // 如果不希望输出负数，可以添加条件判断并返回0
            if (remainingTimeSpan.TotalSeconds < 0)
            {
                return 0;
            }

            // 返回剩余秒数
            return (int)remainingTimeSpan.TotalSeconds;
        }

        string FormatTime(int remainingSeconds)
        {
            // 将剩余秒数转换为TimeSpan对象
            TimeSpan timeSpan = TimeSpan.FromSeconds(remainingSeconds);
            if (timeSpan.TotalHours >= 24)
            {
                // 计算剩余天数和小时数
                int days = (int)timeSpan.TotalDays;
                int hours = (int)timeSpan.Subtract(TimeSpan.FromDays(days)).TotalHours;

                // 格式化为“xxDayxxH”格式的字符串
                string formattedString = $"{days}d: {hours}h";
                return "Ends in "+formattedString;
            }
            else
            {
                // 使用ToString方法将TimeSpan对象转换为格式为“时:分:秒”的字符串
                string formattedString = timeSpan.ToString(@"hh\:mm\:ss");
                return formattedString;
            }


        }
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="args"></param>
        public override void OnClose(params object[] args)
        {
            base.OnClose(args);
            //OnDestroy();
        }
        
        private void OnFirstGetHttpData()
        {
            // if (string.IsNullOrEmpty(HeadsManager.Instance().OnGetLoadHeadKey(1)) == false)
            // {
            //     HeadsManager.Instance().OnEnterLoadHead(HeadsManager.Instance().OnGetLoadHeadKey(1));
            // }
            
            // HttpManager.Instance.GetSigninReward((Datum) =>
            // {
            //     bool isshowredpoint = false;
            //     for (int i = 0; i < Datum.Length; i++)
            //     {
            //         if (Datum[i].Status == 2)
            //         {
            //             isshowredpoint = true;
            //             break;
            //         }
            //     } 
            //     EventCenter.BroadCast<string,bool,int>(EventUtils.EventType.EVENT_REDPOINT, ViewName.ActivityView, isshowredpoint, 0);
            // });
        }
        public void OnInitActivityRedPoint()
        {
            
        }
        private void OnShareRewardHttpData()
        {
        }
        private void OnShowMailRedPoint()
        {
            
        }

        private void SendReferEarnHallReawrdPop()
        {
        }

        void OnUpdataReferEarnInfo()
        {
        }
        
        void OnUpdateMoney()
        {
            try
            {
                if (gameObject.activeSelf)
                {
                    m_txtGold.text = "₹"+Utils._GMoneyFormatDouble(GlobalUserItem.lUserScore);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        void OnUpdateHead()
        {
            mtxtPlayerName.text = GlobalUserItem.szNickName;
            HeadsManager.Instance().OnLoadSelfHead(mimgHead,GlobalUserItem.dwCustomID,GlobalUserItem.wFaceID);
        }

        /// <summary>
        /// 红点
        /// </summary>
        /// <param name="viewname"> 名称 </param>
        /// <param name="isflag"></param>
        /// <param name="redpointnum"> 数量 </param>
        void OnRedpoint(string viewname,bool isflag,int redpointnum)
        {
            if (string.IsNullOrEmpty(viewname))
            {
                return;
            }
            Debug.LogError(viewname+" 的红点显示: "+isflag+" 数量："+redpointnum);
            if (mRedPointDic.ContainsKey(viewname))
            {
                if (redpointnum > 0)
                {
                    mRedPointDic[viewname].SetActive(redpointnum>0);
                }
                else
                {
                    mRedPointDic[viewname].SetActive(isflag);
                }
            }
        }

        void OnDestroy()
        {
            mRedPointDic.Clear();
            // mRedPointDic = null;

            PopActivityManager.Instance().OnBlockOutPopActView();
        }
    }
}